const app = getApp();
Component({
  /**
   * 组件的初始数据
   */
  data: {
    goods: {},
    productImg:"",
    unit: "",
    total: "", //总数量
    price: "", //默认显示的价格
    showSku:false,
    productSpecList:[],//规格
    skus:[],//各种规格的商品
    selectsku:{},//选中的其中一个规格
    curClick: [], //当前被点击的值
    cartnum:1,//数量
    index:0,
    productid:'',//商品id
    supplyChannel:app.supplyChannel,//默认是社区团购
    theme:app.theme,
  },
  observers: {

  },
  attached: function() {
      this.into();
  },
  /**
   * 组件的方法列表
   */
  methods: {
    into(){
      this.setData({
        theme:app.theme
      })
    },
    getProductsDetail(productid,index){
      let that=this;
      that.into();
      that.setData({
        selectsku:{},
        curClick:[],
        goods:app.data.productDetail,
        skus:app.data.productDetail.skus,
        productSpecList:app.data.productDetail.productSpecList,
        showSku:true,
        productImg:app.data.productDetail.thumb,
        unit: app.data.productDetail.unit,
        total:app.data.productDetail.surplus,
        price: app.data.productDetail.marketprice.toFixed(2),
        cartnum:1,
        index:index,
      })
    },
    // 调用接口详情规格
    getProductsDetail1(productid,index,supplyChannel){
      console.log('规格',index)
      this.into();
      let that=this;
      app.api.ProductsDetail({productId: productid},(response)=>{
        that.setData({
          selectsku:{},
          curClick:[],
          goods:response.data,
          skus:response.data.skus,
          productSpecList:response.data.productSpecList,
          showSku:true,
          unit: response.data.unit,
          total: (!isNaN(parseInt(response.data.remainderStock)))? response.data.remainderStock : (response.data.total - response.data.salesreal), //总数量
          price: response.data.marketprice.toFixed(2),
          cartnum:1,
          type:'',
          index:index,
          supplyChannel:supplyChannel
        })
      },(error)=>{

      })
    },
    onClose(){
      this.setData({
        showSku:false
      })
    },
    handleClose(){
      this.setData({
        showSku:false
      })
    },
    handleBtn(e) {
      let index=e.currentTarget.dataset.index;
      let ind=e.currentTarget.dataset.ind;
      var id=this.data.productSpecList[index].specItemList[ind].id;
      this.setData({
        ["curClick["+index+"]"]:id
      })
      let prspeclen = this.data.productSpecList.length;
      if(prspeclen==this.data.curClick.length){
        this.data.skus.forEach((item)=>{
          console.info(item.specs.split("_").map(Number).sort());
          // 判断选中的是哪一个规格
          if(this.data.curClick.toString()==item.specs.split("_").map(Number).sort().toString()){
            this.setData({
              cartnum:1,//每当点击的规格发生变化时就将input初始值设为1
              selectsku:item,
              total:item.stock,
              productImg:item.thumb,
              price:item.marketprice.toFixed(2)
            })
            return;
          }
        })
      }
    },
    // 修改数量
    updateCart(e){
      this.setData({
        cartnum:e.detail
      })
    },
    sort(arr){
      for(var j=0;j<arr.length-1;j++){
      //两两比较，如果前一个比后一个大，则交换位置。
         for(var i=0;i<arr.length-1-j;i++){
              if(arr[i]>arr[i+1]){
                  var temp = arr[i];
                  arr[i] = arr[i+1];
                  arr[i+1] = temp;
              }
          } 
      }
  },
  
    //加入购物车
    addSkuCart(){
      let that=this;
      let userinfo = app.functions.getLocalStorage("user");
      let shop=app.functions.getLocalStorage("shop");
      if(app.functions.isEmpty(userinfo)){
        app.functions.islogin();
        return false;
      }
      if(app.functions.isEmpty(that.data.selectsku)){
        app.functions.showToast("请选择规格！");
        return false;
      }
       let cart={
        mid:userinfo.id,
        teamid:shop.id,
        productId:that.data.goods.id,
        goodsTitle:that.data.goods.title,
        thumb:that.data.goods.thumb,
        total: that.data.cartnum,
        marketprice: that.data.selectsku.marketprice,
        skuId:that.data.selectsku.id,
        skuTitle:that.data.selectsku.title
      };
      wx.vibrateShort();
      app.cartNumber = app.cartNumber == 0 ? cart.total : parseInt(app.cartNumber) + cart.total;
      app.UpdateCart();
      app.cart.push(cart);
      // if (that.data.goods.usermaxbuyNumber && (that.data.goods.cartNum + cart.total) > that.data.goods.usermaxbuyNumber) {
      //   app.functions.showToast("已经超过单次购买数量");
      //   return;
      // }
      // app.api.cartAdd(cart,(response)=>{
      //   if(response.code!=0){
      //     app.functions.showToast("加入到购物车失败");
      //     return ;
      //   }
      //   wx.vibrateShort();
      //   app.cartNumber = app.cartNumber == 0 ? cart.total : parseInt(app.cartNumber) + cart.total;
      //   app.UpdateCart();
      //   that.onClose();
      // },(error)=>{
      //   app.functions.showToast(error.msg);
      // })
    },
    // 立即购买
    addSkuBuy(){
      let that=this;
      let userinfo = app.functions.getLocalStorage("user");
      if(app.functions.isEmpty(userinfo)){
        app.functions.islogin();
        return false;
      }
      if(app.functions.isEmpty(that.data.selectsku)){
        app.functions.showToast("请选择规格！");
        return false;
      }
      let shop=app.functions.getLocalStorage("shop");
      if(app.functions.isEmpty(that.data.selectsku)){
        app.functions.showToast("请选择规格！");
        return false;
      }
       let cart={
        supplyChannel:that.data.supplyChannel,
        mid:userinfo.id,
        teamid:shop.id,
        productId:that.data.goods.id,
        total: that.data.cartnum,
        marketprice: that.data.selectsku.marketprice,
        skuId:that.data.selectsku.id,
        skuTitle:that.data.selectsku.title
      };
      if (that.data.goods.usermaxbuy && (that.data.goods.cartNum + cart.total) > that.data.goods.usermaxbuy) {
        app.functions.showToast("已经超过单次购买数量");
        return;
      }
      app.order={
        cartItems:[cart]
      }
      app.youhuiMon=0;

      let params = {
        memberId: userinfo.id,
        products: cart,
        discountAmount: app.youhuiMon
      };
      // 判断是否直接下单是否有限制
      app.api.orderPrecreate(params,(response)=>{
        // 团购商品直接下单
        if(app.supplyChannel==2){
          wx.navigateTo({
            url: '/pages_subpack/place_order_entity/place_order_entity'
          })
        }else{
          wx.navigateTo({
            url: '/pages_news/create_order/create_order'
          })
        }
      },(error)=>{
        app.functions.showToast(error.msg);
      })
    },
    // 在商品详情中跳过来
    selectsuk(goods,type){
      let that=this;
      that.setData({
        selectsku:{},
        curClick:[],
        goods:goods,
        skus:goods.skus,
        productSpecList:goods.productSpecList,
        showSku:true,
        unit: goods.unit,
        total: (!isNaN(parseInt(goods.remainderStock)))? goods.remainderStock : (goods.total - goods.salesreal), //总数量
        price: goods.marketprice.toFixed(2),
        cartnum:1,
        type:type
      })
    }

  }
})
